<?php

namespace App\Http\Controllers\Api;

use App\Models\Appoint;
use App\Models\Hero;
use App\Services\AppointService;
use Dingo\Api\Http\Request;
use Illuminate\Support\Facades\Redis;

class AppointController extends BaseController
{
    public function index(Request $request) {
        $input = $request->input();
        $func = function () use($input) {
            $query = Hero::select('id', 'heros.username','heros.area', 'heros.row', 'heros.seat', 'heros.pv_num');
            if (!empty($input['username'])) {
                $query = $query->where('heros.username', 'like', '%' . $input['username'] . '%');
            }
            $list = $query->paginate(\request('per_page', 20));
            return $list;
        };
        $list = $this->cache($input, Hero::class, $func);
        return $this->paginate($list);
    }

    public function info(Request $request) {
        $this->validate($request, [
            'id' => 'required',
        ]);
        $id = \request('id');
        $info = Hero::find($id);
        if (!$info)
            return $this->failed("id不存在");
        $info->increment('pv_num');
        return $this->success($info);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
           'date' => 'required|date',
            'time' => 'required',
            'realname' => 'required',
            'phone' => 'regex:/^1[345789][0-9]{9}$/',
            'username' => 'required'
        ]);
        $input = $request->input();
        \Log::info('test111' . var_export($input, true));
        $user = $this->getUser();
        if (!$user)
            return $this->failed("获取用户信息异常，请重新授权", 401);

        \Log::info("user_id" . $user->id);
        $cache_key = "my:lock1:" . $user->id;
        if (Redis::setnx($cache_key, 1)) {
            Redis::expire($cache_key, 10);
            try {
                $heros = Hero::where('contact_name', $input['realname'])->dontRemember()->get();
                if ($heros->count() == 0) {
                    throw new \Exception("购买人姓名错误，如遗忘请拨打电话0790-6661444");
                }
                $hero = null;
                foreach ($heros as $item) {
                    if ($item->username == $input['username']) {
                        $hero = $item;
                        break;
                    }
                }
                if (!$hero) {
                    throw new \Exception("逝者姓名错误，如遗忘请拨打电话0790-6661444");
                }
                $appoint_user_exist = Appoint::where('user_id', $user->id)->exists();
                if ($appoint_user_exist) {
                    throw new \Exception("一个微信号只能预约一次");
                }

                $appoint_hero_exist = Appoint::where('hero_id', $hero->id)->exists();
                if ($appoint_hero_exist) {
                    throw new \Exception("同一个姓名和墓碑位置只能预约一次");
                }

                $date = \request('date');
                $time = \request('time');
                $origin_order_no = AppointService::getOrderNo($date, $time);
                if (!$origin_order_no) {
                    throw new \Exception("当天已预约满");
                }

                $order_no =date('md', strtotime($date)) . str_pad($origin_order_no,4,"0",STR_PAD_LEFT);
                $data = [
                    'order_no' => $order_no,
                    'user_id' => $user->id,
                    'hero_id' => $hero->id,
                    'date' => $input['date'],
                    'time' => $input['time'],
                    'realname' => $input['realname'],
                    'phone' => $input['phone'],
                    'creatd_at' => date('Y-m-d H:i:s')
                ];
                try {
                    Appoint::insert($data);
                } catch (\Exception $e) {
                    AppointService::insertOrderNoToCache($origin_order_no, $date, $time);
                    throw new \Exception("预约失败");
                }
                Redis::del($cache_key);
                return $this->success([], '预约成功');
            } catch (\Exception $e) {
                Redis::del($cache_key);
                return $this->failed($e->getMessage());
            }
        }
        return $this->failed('请勿频繁提交，稍后再试');
    }
}